import json

from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import User
from md import settings


class QQLoginURLView(View):
    def get(self, request):
        """
        登录页面点击qq，请求视图，返回要跳转到的qq登录页面的url，前端进行跳转
        """
        from QQLoginTool.QQtool import OAuthQQ
        # 初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        login_url = oauth.get_qq_url()  # 通过OAuthQQ对象获取要跳转到的qq授权页面url

        return JsonResponse({'code': 0, 'login_url': login_url})


class OauthView(View):
    def get(self, request):
        """
        qq登录成功后，请求视图，url中带有code，通过code获取token，通过token获取openid
        """
        code = request.GET.get('code')
        print(code)
        # 2根据code获取token
        # 2.1导入
        from QQLoginTool.QQtool import OAuthQQ
        # 2.2初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        access_token = oauth.get_access_token(code)
        # 3根据token获取openid
        openid = oauth.get_open_id(access_token)
        # 4 根据openid去数据库查询OAuthQQUser 帐号数据
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            print(e)
            # 4.1如果不存在   捕获异常   走没有绑定的逻辑 去绑定页面
            # 前段分析后 返回openid  key叫做access_token

            openid = generate_access_token(openid)  # 对openid进行加密
            return JsonResponse({"code": 400, "access_token": openid})
        else:
            # 4.2如果存在  正常返回数据  做登录状态保持
            # session
            login(request, qquser.user)
            # cookie
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("username", qquser.user.username)

            return response

    def post(self, request):
        # 1 接收请求
        body = request.body
        data_dict = json.loads(body)

        # 2 获取请求参数  手机号 密码 短信验证码openid
        password = data_dict.get("password")
        mobile = data_dict.get("mobile")
        sms_code = data_dict.get("sms_code")
        openid = data_dict.get("access_token")
        openid = check_access_token(openid)
        # 验证参数（省略）

        # 3 根据手机号  查询是否已经注册
        try:
            user = User.objects.get(mobile=mobile)

        except Exception as e:
            print(e)
            # 5 没有注册  创建一个user对象 绑定  用户和openid
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 4 已经注册  密码验证  密码正确 直接绑定  用户和openid
            if not user.check_password(password):
                return JsonResponse({"code": 400, "errmsg": "账号或者密码错误"})

        try:
            # 绑定user和openid
            OAuthQQUser.objects.create(user=user, openid=openid)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "账号已经绑定 无法添加"})

        # 6 状态保持
        login(request, user)
        response = JsonResponse({"code": 0, "errmsg": "ok"})
        response.set_cookie("username", user.username)

        # 7 返回响应
        return response
